<!--
  智慧社区管理系统 - 权限管理
  @author Wu.Liang
  @date 2024-01-01
  @updated 2025-01-21 - 修复静态数据问题，使用真实API接口，支持树形结构展示
-->
<template>
  <div class="permission-container">
    <div class="header">
      <h1>权限管理</h1>
      <p>管理系统权限信息和菜单配置</p>
    </div>

    <!-- 工具栏 -->
    <div class="toolbar">
      <div class="search-area">
        <el-input v-model="queryParams.keyword" placeholder="请输入权限名称或编码" clearable @keyup.enter="handleSearch"
          style="width: 300px">
          <template #prefix>
            <el-icon>
              <Search />
            </el-icon>
          </template>
        </el-input>
        <el-select v-model="queryParams.status" placeholder="状态筛选" clearable style="width: 120px">
          <el-option label="启用" :value="1" />
          <el-option label="禁用" :value="0" />
        </el-select>
        <el-button type="primary" @click="handleSearch">
          <el-icon>
            <Search />
          </el-icon>
          搜索
        </el-button>
        <el-button @click="resetSearch">
          <el-icon>
            <Refresh />
          </el-icon>
          重置
        </el-button>
      </div>
      <div class="action-area">
        <PermissionGuard permission="permission:menu">
          <el-button type="primary" @click="handleCreate">
            <el-icon>
              <Plus />
            </el-icon>
            新增权限
          </el-button>
        </PermissionGuard>
        <el-button @click="handleExpandAll">
          <el-icon>
            <Sort />
          </el-icon>
          {{ expandAll ? '收起' : '展开' }}
        </el-button>
        <el-button @click="refreshData">
          <el-icon>
            <Refresh />
          </el-icon>
          刷新
        </el-button>
      </div>
    </div>

    <!-- 权限树表格 -->
    <el-table 
      v-loading="loading" 
      :data="permissionList" 
      row-key="id" 
      border 
      stripe
      :tree-props="{ children: 'children', hasChildren: 'hasChildren' }" 
      :default-expand-all="expandAll"
      style="width: 100%"
    >
      <el-table-column prop="permissionName" label="权限名称" min-width="200">
        <template #default="{ row }">
          <el-icon v-if="row.permissionType === 1" class="menu-icon">
            <Menu />
          </el-icon>
          <el-icon v-else class="button-icon">
            <Operation />
          </el-icon>
          <span :style="{ marginLeft: row.parentId ? '20px' : '0' }">
            {{ row.permissionName }}
          </span>
        </template>
      </el-table-column>
      <el-table-column prop="permissionCode" label="权限编码" min-width="180" />
      <el-table-column prop="type" label="权限类型" width="100" align="center">
        <template #default="{ row }">
          <el-tag type="primary" v-if="row.permissionType === 1">
            菜单权限
          </el-tag>
          <el-tag type="success" v-else>
            按钮权限
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="path" label="路由路径" min-width="150" />
      <el-table-column prop="component" label="组件路径" min-width="180" show-overflow-tooltip />
      <el-table-column prop="sortOrder" label="排序" width="80" align="center" />
      <el-table-column prop="status" label="状态" width="100" align="center">
        <template #default="{ row }">
          <el-tag :type="row.status === 1 ? 'success' : 'danger'">
            {{ row.status === 1 ? '启用' : '禁用' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" width="180" />
      <el-table-column label="操作" width="200" fixed="right">
        <template #default="{ row }">
          <el-button type="primary" link @click="handleAddChild(row)" v-if="row.permissionType === 1">
            <el-icon>
              <Plus />
            </el-icon>
            新增子权限
          </el-button>
          <el-button type="warning" link @click="handleEdit(row)">
            <el-icon>
              <Edit />
            </el-icon>
            编辑
          </el-button>
          <el-button type="danger" link @click="handleDelete(row)" v-if="!row.children || row.children.length === 0">
            <el-icon>
              <Delete />
            </el-icon>
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 权限表单对话框 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="700px" @close="resetForm">
      <el-form ref="formRef" :model="form" :rules="rules" label-width="120px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="权限名称" prop="permissionName">
              <el-input v-model="form.permissionName" placeholder="请输入权限名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="权限编码" prop="permissionCode">
              <el-input v-model="form.permissionCode" placeholder="请输入权限编码" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="权限类型" prop="type">
              <el-radio-group v-model="form.permissionType" disabled>
                <el-radio :value="1">菜单权限</el-radio>
              </el-radio-group>
              <div class="form-tip">
                <el-icon><InfoFilled /></el-icon>
                <span>权限系统已简化，仅支持菜单级权限控制</span>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="排序" prop="sortOrder">
              <el-input-number v-model="form.sortOrder" :min="0" :max="999" style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20" v-if="form.permissionType === 1">
          <el-col :span="12">
            <el-form-item label="路由路径" prop="path">
              <el-input v-model="form.path" placeholder="请输入路由路径" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="组件路径" prop="component">
              <el-input v-model="form.component" placeholder="请输入组件路径" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio :value="1">启用</el-radio>
            <el-radio :value="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="备注" prop="description">
          <el-input v-model="form.description" type="textarea" :rows="3" placeholder="请输入备注信息" />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessageBox } from 'element-plus'
import { Search, Refresh, Plus, Sort, Edit, Delete, Menu, Operation, InfoFilled } from '@element-plus/icons-vue'
import PermissionGuard from '@/components/PermissionGuard.vue'
import { getCompletePermissionTree, createPermission, updatePermission, deletePermission } from '@/api/permission'
import { showMessage } from '@/utils/message'

// 权限数据接口
interface Permission {
  id: number
  permissionName: string
  permissionCode: string
  permissionType: number
  parentId?: number
  path?: string
  component?: string
  icon?: string
  sortOrder: number
  status: number
  description?: string
  createTime: string
  children?: Permission[]
}

// 响应式数据
const loading = ref(false)
const permissionList = ref<Permission[]>([])
const dialogVisible = ref(false)
const dialogTitle = ref('')
const formRef = ref()
const expandAll = ref(false)

// 查询参数
const queryParams = reactive({
  keyword: '',
  status: undefined as number | undefined
})

// 表单数据
const form = reactive({
  id: null as number | null,
  permissionName: '',
  permissionCode: '',
  permissionType: 1,
  parentId: null as number | null,
  path: '',
  component: '',
  icon: '',
  sortOrder: 0,
  status: 1,
  description: ''
})

// 表单验证规则
const rules = {
  permissionName: [
    { required: true, message: '请输入权限名称', trigger: 'blur' },
    { min: 2, max: 50, message: '权限名称长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  permissionCode: [
    { required: true, message: '请输入权限编码', trigger: 'blur' },
    { pattern: /^[a-z]+:menu$/, message: '权限编码格式为 模块:menu（如 user:menu）', trigger: 'blur' }
  ],
  permissionType: [
    { required: true, message: '请选择权限类型', trigger: 'change' }
  ]
}

// 获取权限树数据
const getPermissionTreeData = async () => {
  loading.value = true
  try {
    const params: any = {}
    if (queryParams.status !== undefined) {
      params.status = queryParams.status
    }
    
    const response = await getCompletePermissionTree(params.status)
    if (response.code === 200) {
      permissionList.value = response.data || []
      
      // 如果有搜索关键词，进行本地过滤
      if (queryParams.keyword) {
        permissionList.value = filterPermissionsByKeyword(permissionList.value, queryParams.keyword)
      }
    } else {
      showMessage({ type: 'error', message: response.message || '获取权限树失败' })
    }
  } catch (error) {
    console.error('获取权限树失败:', error)
    showMessage({ type: 'error', message: '获取权限树失败' })
  } finally {
    loading.value = false
  }
}

// 根据关键词过滤权限
const filterPermissionsByKeyword = (permissions: Permission[], keyword: string): Permission[] => {
  const filtered: Permission[] = []
  
  for (const permission of permissions) {
    const matches = permission.permissionName.includes(keyword) || 
                   permission.permissionCode.includes(keyword)
    
    if (matches) {
      // 如果父权限匹配，包含所有子权限
      filtered.push(permission)
    } else if (permission.children && permission.children.length > 0) {
      // 如果子权限匹配，包含父权限和匹配的子权限
      const filteredChildren = filterPermissionsByKeyword(permission.children, keyword)
      if (filteredChildren.length > 0) {
        filtered.push({
          ...permission,
          children: filteredChildren
        })
      }
    }
  }
  
  return filtered
}

// 搜索
const handleSearch = () => {
  getPermissionTreeData()
}

// 重置搜索
const resetSearch = () => {
  queryParams.keyword = ''
  queryParams.status = undefined
  getPermissionTreeData()
}

// 刷新数据
const refreshData = () => {
  getPermissionTreeData()
}

// 展开/收起全部
const handleExpandAll = () => {
  expandAll.value = !expandAll.value
}

// 新增权限
const handleCreate = () => {
  dialogTitle.value = '新增权限'
  resetForm()
  dialogVisible.value = true
}

// 新增子权限
const handleAddChild = (row: Permission) => {
  dialogTitle.value = '新增子权限'
  resetForm()
  form.parentId = row.id
  dialogVisible.value = true
}

// 编辑权限
const handleEdit = (row: Permission) => {
  dialogTitle.value = '编辑权限'
  Object.assign(form, {
    id: row.id,
    permissionName: row.permissionName,
    permissionCode: row.permissionCode,
    permissionType: row.permissionType,
    parentId: row.parentId,
    path: row.path || '',
    component: row.component || '',
    icon: row.icon || '',
    sortOrder: row.sortOrder,
    status: row.status,
    description: row.description || ''
  })
  dialogVisible.value = true
}

// 删除权限
const handleDelete = async (row: Permission) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除权限"${row.permissionName}"吗？删除后无法恢复！`, 
      '删除确认', 
      {
        type: 'warning',
        confirmButtonText: '确定删除',
        cancelButtonText: '取消'
      }
    )
    
    const response = await deletePermission(row.id)
    if (response.code === 200) {
      showMessage({ type: 'success', message: '删除成功' })
      getPermissionTreeData()
    } else {
      showMessage({ type: 'error', message: response.message || '删除失败' })
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除权限失败:', error)
      showMessage({ type: 'error', message: '删除失败' })
    }
  }
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return

  try {
    await formRef.value.validate()
    
    const submitData = {
      permissionName: form.permissionName,
      permissionCode: form.permissionCode,
      permissionType: form.permissionType,
      parentId: form.parentId,
      path: form.path,
      component: form.component,
      icon: form.icon,
      sortOrder: form.sortOrder,
      status: form.status,
      description: form.description
    }
    
    let response
    if (form.id) {
      // 更新权限
      response = await updatePermission(form.id, submitData)
    } else {
      // 新增权限
      response = await createPermission(submitData)
    }
    
    if (response.code === 200) {
      showMessage({ type: 'success', message: form.id ? '编辑成功' : '新增成功' })
      dialogVisible.value = false
      getPermissionTreeData()
    } else {
      showMessage({ type: 'error', message: response.message || (form.id ? '编辑失败' : '新增失败') })
    }
  } catch (error) {
    console.error('表单提交失败:', error)
    showMessage({ type: 'error', message: '操作失败' })
  }
}

// 重置表单
const resetForm = () => {
  formRef.value?.resetFields()
  Object.assign(form, {
    id: null,
    permissionName: '',
    permissionCode: '',
    permissionType: 1,
    parentId: null,
    path: '',
    component: '',
    icon: '',
    sortOrder: 0,
    status: 1,
    description: ''
  })
}

// 页面加载时获取数据
onMounted(() => {
  getPermissionTreeData()
})
</script>

<style scoped>
.permission-container {
  padding: 20px;
}

.header {
  margin-bottom: 20px;
}

.header h1 {
  margin: 0 0 8px 0;
  font-size: 24px;
  color: #333;
}

.header p {
  margin: 0;
  color: #666;
  font-size: 14px;
}

.toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 16px;
  background: #f8f9fa;
  border-radius: 8px;
}

.search-area {
  display: flex;
  gap: 12px;
  align-items: center;
}

.action-area {
  display: flex;
  gap: 12px;
}

.menu-icon {
  color: #409eff;
  margin-right: 8px;
}

.button-icon {
  color: #67c23a;
  margin-right: 8px;
}

.dialog-footer {
  text-align: right;
}

.form-tip {
  display: flex;
  align-items: center;
  gap: 4px;
  margin-top: 4px;
  color: #909399;
  font-size: 12px;
}

/* 树形结构样式 */
.el-table .el-table__row {
  transition: all 0.3s ease;
}

.el-table .el-table__row:hover {
  background-color: #f5f7fa;
}

/* 子权限缩进 */
.el-table .el-table__row .cell {
  padding-left: 20px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .toolbar {
    flex-direction: column;
    gap: 16px;
    align-items: stretch;
  }

  .search-area,
  .action-area {
    flex-wrap: wrap;
  }
}
</style>
